package org.winexpress

import grails.converters.deep.JSON
import org.codehaus.groovy.grails.web.json.JSONObject;
import org.codehaus.groovy.grails.web.json.JSONArray;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;


class LoginController {
    
//    def getSingleShoppingCart(customerId) {
//       
//        // consume winexpress server web service
//        def txt = new URL("http://localhost:8080/WineXpress/customer/" + customerId + "/cart/").text
//        
//        println txt
//        
//        if (txt.getAt(0) == '{') {
//            println 'HERE3'
//            JSONObject o = new JSONObject(txt)
//            if (o.has("404")) {
//                println 'HERE1'
//                if (o.get("404") == true) {
//                    println 'HERE2'
//                    flash.message = 'No specified cart found.<br/><br/>'
//                    try {
//                        redirect(uri:"/404")
//                    }
//                    catch (CannotRedirectException) {
//                        println 'already redirected...'
//                    }
//                }
//            }
//            else { 
////                sc.id = o.get("id")
////                sc.creationDate = o.get("creationDate")
////                sc.modifiedDate = o.get("modifiedDate")
////                sc.customerId = o.get("customerId")
////                if (o.has("uniqueKey")) {
////                    sc.uniqueKey = o.get("uniqueKey")
////                }
////                return sc
//            }
//        }
//        else {
//            println 'HERE5'
//           
//            JSONArray arr = new JSONArray(txt)
//            
//                arr.each()
//                {
//                    println 'HERE4'
//                    ShoppingCart sc = new ShoppingCart()
////                    char[] arrayId = o.get("id").toCharArray()
////                    IntRange rangeId = new IntRange(1,arrayId.length-1)
////
////                    char[] arrayCreationDate = o.get("creationDate").toCharArray()
////                    IntRange rangeCreationDate = new IntRange(1,arrayId.length-1)
////
////                    char[] arrayModifiedDate = o.get("modifiedDate").toCharArray()
////                    IntRange rangeModifiedDate = new IntRange(1,arrayId.length-1)
////
////                    char[] arrayUniqueKey = o.get("customerId").toCharArray()
////                    IntRange rangeUniqueKey = new IntRange(1,arrayId.length-1)
////
////                    char[] arrayCustomerId = o.get("uniqueKey").toCharArray()
////                    IntRange rangeCustomerId = new IntRange(1,arrayId.length-1)
//
////                    sc.id = arrayId.getAt(rangeId)
////                    sc.creationDate = arrayCreationDate.getAt(rangeCreationDate)
////                    sc.modifiedDate = arrayModifiedDate.getAt(rangeModifiedDate)
////                    sc.customerId = arrayCustomerId.getAt(rangeUniqueKey)
////                    sc.uniqueKey = arrayUniqueKey.getAt(rangeCustomerId)
//
//                    IntRange indexRangeYear = new IntRange(0,3)
//                    IntRange indexRangeMonth = new IntRange(5,6)
//                    IntRange indexRangeDay = new IntRange(8,9)
//                    def cdYear = it.creationDate.getAt(indexRangeYear)
//                    def cdMonth = it.creationDate.getAt(indexRangeMonth)
//                    def cdDay = it.creationDate.getAt(indexRangeDay)
//                    Date convertedCD = new Date()
//                    convertedCD.setDate(cdDay.toInteger())
//                    convertedCD.setMonth(cdMonth.toInteger()-1)
//                    convertedCD.setYear(cdYear.toInteger())
//                    convertedCD.setHours(0)
//                    convertedCD.setMinutes(0)
//                    convertedCD.setSeconds(0)
//                    
//                    def mdYear = it.modifiedDate.getAt(indexRangeYear)
//                    def mdMonth = it.modifiedDate.getAt(indexRangeMonth)
//                    def mdDay = it.modifiedDate.getAt(indexRangeDay)
//                    Date convertedMD = new Date()
//                    convertedMD.setDate(mdDay.toInteger())
//                    convertedMD.setMonth(mdMonth.toInteger()-1)
//                    convertedMD.setYear(mdYear.toInteger())
//                    convertedMD.setHours(0)
//                    convertedMD.setMinutes(0)
//                    convertedMD.setSeconds(0)
// 
//            
//                    sc.id = it.id
////                    sc.creationDate = convertedCD
////                    sc.modifiedDate = convertedMD
//                    sc.customerId = customerId
//                    sc.uniqueKey = it.uniqueKey
//                    println sc.id
//                    // todo: STUPID bug =( dont know why it's not working inside here prints 1 but outof this it ptins [1]
//                    return sc
//                }
//        }
//    }

    def getSingleProduct(id) {
       
        // consume winexpress server web service
        def txt = new URL("http://localhost:8080/WineXpress/product/" + id).text
        
        if (txt.getAt(0) == '{') {
            JSONObject o = new JSONObject(txt)
            if (o.has("404")) {
                if (o.get("404") == true) {
                    flash.message = 'No specified product found.<br/><br/>'
                    try {
                        redirect(uri:"/404")
                    }
                    catch (CannotRedirectException) {
                        println 'already redirected...'
                    }
                }
            }
            else {
                Product p = new Product()
                p.id = o.get("id")
                p.productName = o.get("productName")
                p.description = o.get("description")
                p.imageUrl = o.get("imageUrl")
                
                ProductType pt = o.get("productType")
                p.productTypeName = pt.productTypeName
                
                return p
            }
        }
        else {
            flash.message = 'No specified product found.<br/><br/>'
            redirect(uri:"/")
        }
    }
    
    def getSingleCart(id) {
       
        // consume winexpress server web service
        def txt = new URL("http://localhost:8080/WineXpress/cart/" + session.cartId).text
        
        if (txt.getAt(0) == '{') {
            JSONObject o = new JSONObject(txt)
            if (o.has("404")) {
                if (o.get("404") == true) {
                    flash.message = 'No specified cart found.<br/><br/>'
                    try {
                        redirect(uri:"/404")
                    }
                    catch (CannotRedirectException) {
                        println 'already redirected...'
                    }
                }
            }
            else {
                ShoppingCart sc = new ShoppingCart()
                sc.id = o.get("id")
//                sc.creationDate = o.get("creationDate")
//                sc.modifiedDate = o.get("modifiedDate")
                sc.customerId = o.get("customerId")
                sc.uniqueKey = o.get("uniqueKey")
                
                return sc
            }
        }
        else {
            flash.message = 'No specified cart found.<br/><br/>'
            redirect(uri:"/")
        }
    }
    
    def getCartItems(id) {
       
        // consume winexpress server web service
        def txt = new URL("http://localhost:8080/WineXpress/cart/" + session.cartId + "/item/").text
        
        if (txt.getAt(0) == '{') {
            JSONObject o = new JSONObject(txt)
            if (o.has("404")) {
                if (o.get("404") == true) {
                    flash.message = 'No cart items.<br/><br/>'
                    try {
                        redirect(uri:"/404")
                    }
                    catch (CannotRedirectException) {
                        println 'already redirected...'
                    }
                }
            }
        }
        else {
            JSONArray arr = new JSONArray(txt)
            ArrayList<Country> itemList = new ArrayList<Country>()

            arr.each()
            {
                CartItem ci = new CartItem()
                ci.id = it.id
                ci.productId = it.productId
                Product p = getSingleProduct(ci.productId)
                ci.productName = p.productName
                ci.sellingPrice = it.sellingPrice
                println 'it.sellingPrice:: ' + it.sellingPrice
                ci.quantity = it.quantity
//                ci.cartId = it.cartId
            }

            return itemList
        }
    }
    

    def putMemberLogin = {
        def username = params['username']
        def password = params['password']
        
        def encodedPassword = PasswordCodec.encode(password)
        
        println "in login controller"
        
        JSONObject o = new JSONObject()
        o.put("username",username)
        o.put("password",encodedPassword)
        
        // to create use POST
        HttpClient httpclient = new DefaultHttpClient()
        HttpResponse response
        // consume winexpress server web service
        HttpPut httpput = new HttpPut("http://localhost:8080/WineXpress/login") // WineXpress Server's URI
        StringEntity se = new StringEntity(o.toString())          
        httpput.setEntity(se);          
        response = httpclient.execute(httpput);
        
        // get response code
        StatusLine status = response.getStatusLine()
        int statusCode = status.getStatusCode()
        
        println statusCode
        
        if (statusCode == 200) {
            def txtCustomer = new URL("http://localhost:8080/WineXpress/customer/" + username).text
            JSONObject objCustomer = new JSONObject(txtCustomer)
//            println txtCustomer
            session.customerId = objCustomer.id
            session.customerUsername = objCustomer.username
            session.customerName = objCustomer.firstName
            
//            ShoppingCart yourCart = getSingleShoppingCart(session.customerId)
//            println 'yourCart ' + yourCart
            session.cartId = objCustomer.shoppingCartId
            println 'session.cartId:: ' + session.cartId
            session.uniqueKey = objCustomer.uniqueKey
            println session.uniqueKey
            
            ShoppingCart cart = getSingleCart()
            CartItem cartItems = getCartItems(cart.id)
//            session.cartItemCount = cartItems.size()
            flash.message = 'Account login success.'
            redirect(uri:"/")
        }
        if (statusCode == 400) {
            flash.message = 'Failed to receive username and password received.'
            redirect(uri:"/memberLogin")
        }
        if (statusCode == 403) {
            flash.message = 'Wrong username/password combination. Please try again.'
            redirect(uri:"/memberLogin")
        }
        if (statusCode == 404) {
            flash.message = 'Account could not be found or it may not have been activated.'
            redirect(uri:"/memberLogin")
        }
        
        println "updateMemberLastLogin OK"
        
//        // consume winexpress server web service
//        def txt = new URL("http://localhost:8080/WineXpress/login/" + username + "/" + password).text
//
//        JSONObject o  = new JSONObject(txt)
//        
//        if (o.has("404")) {
//            if (o.get("404") == true) {
//                flash.message = 'User not found.<br/><br/>'
//
//                redirect(uri:"/memberLogin")
//            }
//        }
//        else {
//            if (password == o.password) {
//                session.customerId = o.id
//                session.customerUsername = o.username
//                session.customerName = o.firstName
//
//                println "Login Details: " + session.customerId + " " + session.customerName
//            }
//            else {
//                flash.message = "Wrong credentials.<br/><br/>"
//            }
//
//            println "updateMemberLastLogin OK"
//
//            redirect(uri:"/")
//        }
    }
    
    def memberLogout = {
        session.customerId = null
        session.customerUsername = null
        session.customerName = null
        
        flash.message = 'You have been logged out successfully. Thank you! Please come again!'
        
        redirect(uri:"/")
    }
    
    
    def passwordReset = {
        def username = params['username']
        def email = params['email']
        
        println "in forgot controller"
        
        JSONObject o = new JSONObject()
        o.put("username",username)
        o.put("email",email)
        
        // to create use POST
        HttpClient httpclient = new DefaultHttpClient()
        HttpResponse response
        // consume winexpress server web service
        HttpPut httpput = new HttpPut("http://localhost:8080/WineXpress/login/forgot") // WineXpress Server's URI
        StringEntity se = new StringEntity(o.toString())          
        httpput.setEntity(se);          
        response = httpclient.execute(httpput);
        
        // get response code
        StatusLine status = response.getStatusLine()
        int statusCode = status.getStatusCode()
        
        println statusCode
        
        if (statusCode == 200) {
            def txtCustomer = new URL("http://localhost:8080/WineXpress/customer/" + username).text
            JSONObject objCustomer = new JSONObject(txtCustomer)
            session.customerId = objCustomer.id
            session.customerUsername = objCustomer.username
            session.customerName = objCustomer.firstName
            flash.message = 'Account login success.'
            redirect(uri:"/")
        }
        if (statusCode == 400) {
            flash.message = 'Failed to receive username and password received.'
            redirect(uri:"/memberLogin")
        }
        if (statusCode == 403) {
            flash.message = 'Wrong username/password combination. Please try again.'
            redirect(uri:"/memberLogin")
        }
        if (statusCode == 404) {
            flash.message = 'Account could not be found or it may not have been activated.'
            redirect(uri:"/memberLogin")
        }
        
        println "updateMemberLastLogin OK"
    }
}
